using System.Diagnostics;
using Dapper.Abstractions;
using Dapper.Bulk;

namespace DataAccess.Api.Endpoints.Blog;

public class BulkInsert : IEndpoint
{
    public void MapEndpoint(IEndpointRouteBuilder app)
    {
	    // 批量插入示例
        app.MapPost("/api/blogs/dapper-bulk-insert", async (IDbConnectionFactory dbConnectionFactory) =>
        {
            var blogs = DataGenerator.GenerateBlogs(100000);
            // 计时
            var sw = Stopwatch.StartNew();
            
            // 配置实体映射
            BulkManager.Entity<Models.Blog>()
                .Table("blogs")
                .Identity(x => x.Id)
                .UseBulkOptions(options =>
                {
                    options.BatchSize = 1000; // 增加批次大小可能进一步提升性能
                });
            
            using var connection = await dbConnectionFactory.CreateConnectionAsync();

            // 使用批量插入
            await connection.BulkInsertAsync(blogs);
            
            sw.Stop();
            Console.WriteLine($"Elapsed time: {sw.ElapsedMilliseconds} ms");
            return Results.Ok("100,000 blogs inserted using custom bulk insert.");
        })
        .WithName("DapperBulkInsertBlogs")
        .WithTags(Tags.Blog);
    }
}
